package cn.edu.zafu.bigdata.yuyini;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class FileWriteRead {

    // 将用户输入的文本写入到指定的文件中
    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文本已成功写入到文件中。");
        } catch (IOException e) {
            System.out.println("发生错误：无法写入文件。");
            e.printStackTrace();
        }
    }

    // 从文件中读取内容并打印
    public static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("发生错误：无法读取文件。");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入文本：");
        String content = scanner.nextLine();

        // 使用学号202211080202作为文件名
        String studentID = "202211080202";
        String fileName = "files/" + studentID + ".txt";

        // 确保files目录存在
        File directory = new File("files");
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 写入文件
        writeToFile(fileName, content);

        // 读取并显示文件内容
        System.out.println("文件内容：");
        readFromFile(fileName);
    }
}